package com.xcw.jac.des;

import javax.crypto.*;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

public class Decryptor {
    private PrivateKey privateKey;

    public Decryptor(String privateKeyStr) {
        try {
            // 将Base64编码的字符串转换为私钥对象
            byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyStr);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            this.privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            e.printStackTrace();
        }
    }

    public String decrypt(String encryptedPassword) {
        try {
            // 创建密码器
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);

            // 解密密码
            byte[] encryptedBytes = Base64.getDecoder().decode(encryptedPassword);
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

            // 将解密后的字节数组转换为字符串
            return new String(decryptedBytes);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        String encryptedPassword = "bcpmjJYs0ytPlS+bYHLGyDQJnblalzLXw++timJeIklDwiTMkeer0A65yocBBr8G2C07iLdbRQfw2urXJXDtYg=="; // 加密后的密码
        String privateKeyStr = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAotT802octiiOwACOQ4s8N//4B+HVaCJMH8AzHsb6PGabF3rL1jrnGBf9UQR+kC4C/syVeU47D7371xvTSjcIbwIDAQABAkEAlb7l289kJClcTjq0mm07rgxan3USeze/ZhutZ4p5qn0CInYa1BnIehYNGMgv2jeTgR+X+OiZR3DzZuvo0TR40QIhANSbM9ajW1x79sywQw7f5CDKTQTfazxfHxkNL5DFDmw7AiEAxBENCovJ8/MiX85k9LQJkX+kLr5uIqqhcHh94lEctV0CIEc1DDGxWOIq6sg3qN4Mgt2wpAcjxUjdGw9K6Ul1lpUNAiAKzM2lGRIkx+3KzTmuaQRl6VwH3yF981w1L83vW3xzWQIhAJpD/84b7RccAkgUdinnXoHl7vAdFenKcrj77fzL+wDA"; // 私钥

        Decryptor decryptor = new Decryptor(privateKeyStr);
        String decryptedPassword = decryptor.decrypt(encryptedPassword);

        System.out.println("Decrypted Password: " + decryptedPassword);
    }
}